package com.example.online.music.algorithm;

import com.example.online.music.model.domain.Collect;
import com.example.online.music.model.domain.DownloadRecord;
import com.example.online.music.model.domain.PlayRecord;
import com.example.online.music.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

@Component
public class RecommendTask {

    @Autowired
    private RecommendService recommendService;
    @Autowired
    private DownLoadRecordService downLoadRecordService;
    @Autowired
    private PlayRecordService playRecordService;
    @Autowired
    private CollectService collectionService;
    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private SongService songService;

    /**
     * KNN k值
     * 目前系统用户很少
     */
    public static final int K = 10;

    /**
     * 基于最近邻用户的协同过滤给用户推荐歌曲的数量 n值
     * 歌曲很少
     */
    public static final int N = 15;

    /**
     * @Description: 定时任务，10秒执行一次
     * @Author: yang_yong
     * @CreateTime:
     **/
//    @Scheduled(cron = "*/30 * * * * ?")
    @Scheduled(cron = "0 */10 * * * ?") //每十分钟执行一次
    public void recommend(){
//        System.out.println(System.currentTimeMillis() + " ------------开始执行任务-------------");
        //用户-歌曲 推荐列表
        Map<Integer, Integer[]> user2songRecMatrix = new HashMap<Integer, Integer[]>();
        //获取用户
        List<Integer> userIdList = consumerService.getAllUserIds();
        //获取歌曲
        List<Integer> songIdList = songService.getAllSongIds();
        //获取用户的播放记录
        List<PlayRecord> playList = playRecordService.getAllRecords();
        //获取用户的下载记录
        List<DownloadRecord> downloadList = downLoadRecordService.getAllRecords();
        //获取用户的收藏记录
        List<Collect> collectionList = collectionService.getAllRecords();
        //用户-歌曲 “评分”矩阵
        Map<Integer, float[]> user2songRatingMatrix = DataTranslate.getFrequencyMatrix(userIdList, songIdList,
                downloadList, playList, collectionList);
        //用户相似性计算，获取用户的k个近邻用户
        Map<Integer, Integer[]> userKNNMatrix = UserKNN.getKNN(userIdList, user2songRatingMatrix, K);
        //基于用户相似性的协同过滤
        user2songRecMatrix = CollaborativeFiltering.userKNNBasedCF(userIdList, userKNNMatrix,
                user2songRatingMatrix, songIdList, N);
        //打印推荐数据
//        user2songRecMatrix.forEach((userId, songIds) -> System.out.println("为用户id = " + userId + "推荐的歌曲是：" + Arrays.toString(songIds)));

//        System.out.println("------------执行任务完成-------------");
        //向推荐列表中更新写数据
        recommendService.updatePersonalRecInfo(user2songRecMatrix);
    }
}
